package cn.net.shuxing.yifu.common.service;

import cn.net.shuxing.yifu.common.constant.CodeConst;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.util.JedisUtil;
import cn.net.shuxing.yifu.common.util.SMSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.Random;

@Service("smsUserService")
public class SmsUserService {

    @Autowired
    private SMSUtil smsUtil;

    @Autowired
    private JedisUtil jedisUtil;

    public BaseDto sendSMS(String phoneNum, String redisKey) {
        //Jedis //jedis = jedisUtil.getJedis();
        if ("1".equals(jedisUtil.get(redisKey + "timeout"))) {
            //jedisUtil.close();
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("1分钟内只能发送一次手机验证码");
            return baseDto;
        }

        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            builder.append(Math.abs(random.nextInt() % 10));
        }
        String code = builder.toString();

        if (smsUtil.sendShortMsg(phoneNum, code)) {
            BaseDto baseDto = new BaseDto();
            baseDto.setData("手机验证码发送成功");
            jedisUtil.set(redisKey,code);
            jedisUtil.expire(redisKey,60 * 5 );
            jedisUtil.set(redisKey + "timeout","1");
            jedisUtil.expire(redisKey + "timeout" ,60 );
//            jedisUtil.setex(redisKey, 10 , code);
//            jedisUtil.setex(redisKey + "timeout", 20, "1");
            //jedisUtil.close();
            return baseDto;
        } else {
            BaseDto baseDto = new BaseDto();
            baseDto.setCode(CodeConst.ERROR);
            baseDto.setMsg("手机验证码发送失败");
            return baseDto;
        }
    }
}
